package com.bw.goods_module.category;

import com.bw.common.mvvm.model.BaseRespository;
import com.bw.network_sdk.BaseEntity;
import com.bw.network_sdk.HttpType;
import com.bw.network_sdk.NetWorkFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;

public class CategoryRepository extends BaseRespository {

    //创建虚拟左侧列表数据被观察者
    private Observable<CategoryEntity>requestCategory(){
        List<CategoryEntity.Value>data = new ArrayList<>();
        for (int i = 0;i < 6;i ++){
            CategoryEntity.Value value = new CategoryEntity.Value();
            value.parent_id = i;
            value.name = "贾一璠"+i;
            value.selFlag = false;
            if (i==0)
                value.selFlag = true;
            data.add(value);
        }
        CategoryEntity entity = new CategoryEntity();
        entity.status = 200;
        entity.message = "请求成功";
        entity.data = data;
        return Observable.just(entity);
    }

    //创建获取右侧列表方法
    public Observable<BaseEntity>requestCategoryValue(Map<String,Object>map){
        Observable<CategoryValueEntity>categoryValueEntityObservable =
                NetWorkFactory.factory(HttpType.TOKENSIGN)
                        .create(ApiService.class)
                        .requestCategoryValue(createBody(map));
        return checkNetWork(categoryValueEntityObservable);
    }

    //初次进入界面使用flatmap操作符获取左侧以及右侧列表数据且合并为一个Observable
    public Observable<BaseEntity>request(){
        Observable<CategoryEntity> categoryEntityObservable = requestCategory();
        Observable<BaseEntity> observable = categoryEntityObservable.flatMap(new Function<CategoryEntity,
                ObservableSource<BaseEntity>>() {
            @Override
            public ObservableSource<BaseEntity> apply(
                    @NonNull CategoryEntity categoryEntity) throws Exception {
                long parent_id = 0;
                for (int i = 0;i < categoryEntity.data.size();i ++){
                    if (categoryEntity.data.get(i).selFlag)
                        parent_id = categoryEntity.data.get(i).parent_id;
                }
                //构建获取右侧列表请求
                Map<String,Object>map = new HashMap<>();
                map.put("parentId",parent_id);
                //构建右侧列表被观察者任务
                Observable<BaseEntity> categoryValueObservable = requestCategoryValue(map);
                //重新构建左侧被观察者任务
                Observable<CategoryEntity> categoryObservable = Observable.just(categoryEntity);
                //合并左侧以及右侧被观察者任务为一个被观察者任务->vm统一订阅处理
                return mergeObservable(categoryObservable,categoryValueObservable);
            }
        });
        return observable;
    }


}
